package com.xxl.job.admin.repository;

import com.xxl.job.admin.core.conf.XxlJobAdminConfig;
import com.xxl.job.admin.core.enums.DatabaseTypeEnum;
import com.xxl.job.admin.core.model.QueryParam;
import com.xxl.job.admin.core.model.XxlJobInfo;
import com.xxl.job.admin.dao.XxlJobInfoDao;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class XxlJobInfoRepository implements XxlJobInfoDao {

    private final XxlJobInfoDao xxlJobInfoDao;

    public XxlJobInfoRepository(XxlJobInfoDao xxlJobInfoDao) {
        this.xxlJobInfoDao = xxlJobInfoDao;
    }

    @Override
    public List<XxlJobInfo> pageList(int offset, int pagesize, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {
        return xxlJobInfoDao.pageList(offset, pagesize, jobGroup, triggerStatus, jobDesc, executorHandler, author);
    }

    @Override
    public int pageListCount(int offset, int pagesize, int jobGroup, int triggerStatus, String jobDesc, String executorHandler, String author) {
        return xxlJobInfoDao.pageListCount(offset, pagesize, jobGroup, triggerStatus, jobDesc, executorHandler, author);
    }

    @Override
    public int save(XxlJobInfo info) {
        DatabaseTypeEnum typeEnum = DatabaseTypeEnum.getByType(XxlJobAdminConfig.getAdminConfig().getDatabaseId());
        switch (typeEnum) {
            case MYSQL:
                return xxlJobInfoDao.save(info);
            case ORACLE:
                // 从Oracle序列中获取ID并设值
                info.setId(xxlJobInfoDao.getNextOracleSequenceId());
                return xxlJobInfoDao.saveWithId(info);
            default:
                throw new RuntimeException("un support database type");
        }
    }

    @Override
    public int getNextOracleSequenceId() {
        return xxlJobInfoDao.getNextOracleSequenceId();
    }

    @Override
    public int saveWithId(XxlJobInfo info) {
        return xxlJobInfoDao.saveWithId(info);
    }

    @Override
    public XxlJobInfo loadById(int id) {
        return xxlJobInfoDao.loadById(id);
    }

    @Override
    public int update(XxlJobInfo xxlJobInfo) {
        return xxlJobInfoDao.update(xxlJobInfo);
    }

    @Override
    public int delete(long id) {
        return xxlJobInfoDao.delete(id);
    }

    @Override
    public List<XxlJobInfo> getJobsByGroup(int jobGroup) {
        return xxlJobInfoDao.getJobsByGroup(jobGroup);
    }

    @Override
    public int findAllCount() {
        return xxlJobInfoDao.findAllCount();
    }

    @Override
    public List<XxlJobInfo> scheduleJobQuery(long maxNextTime, int pagesize) {
        return xxlJobInfoDao.scheduleJobQuery(maxNextTime, pagesize);
    }

    @Override
    public int scheduleUpdate(XxlJobInfo xxlJobInfo) {
        return xxlJobInfoDao.scheduleUpdate(xxlJobInfo);
    }

    @Override
    public List<XxlJobInfo> getListByIds(QueryParam queryParam) {
        return xxlJobInfoDao.getListByIds(queryParam);
    }
}
